package com.ruoyi.consumer.controller;

import com.github.pagehelper.PageInfo;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.CustomExcelExporter;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.consumer.domain.CStatisticTable;
import com.ruoyi.consumer.domain.param.CStatisticTableParam;
import com.ruoyi.consumer.service.ICStatisticTableService;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 统计总Controller
 *
 * @author YFENTEST
 * @date 2024-03-11
 */
@RestController
@RequestMapping("/consumer/statistic")
public class CStatisticTableController extends BaseController {
    @Autowired
    private ICStatisticTableService cStatisticTableService;

    private static  String price = "";
    @Autowired
    private ISysDeptService sysDeptService;

    public TableDataInfo getDataTable(List<CStatisticTable> list, List<?> list1) {
        // 使用原始 list 创建 PageInfo 对象来保留分页信息
        PageInfo<CStatisticTable> pageInfo = new PageInfo<>(list);
        TableDataInfo rspData = new TableDataInfo(list1, (int) pageInfo.getTotal());
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setMsg("查询成功");
        rspData.setRows(list1);
        rspData.setTotal(new PageInfo(list).getTotal());
        return rspData;
    }

    //将分换成元保留两位小数
    public String getMoney(Integer money) {
        String str = String.valueOf(money);
        if (str.length() == 1) {
            str = "0.0" + str;
        } else if (str.length() == 2) {
            str = "0." + str;
        } else {
            str = str.substring(0, str.length() - 2) + "." + str.substring(str.length() - 2);
        }
        return str;
    }

    // 将克(g)转换为千克(kg)并保留两位小数
    public String getKg(Integer g) {
        double kg = g / 1000.0; // 将克转换为千克
        // 使用DecimalFormat来保留两位小数并格式化输出
        DecimalFormat df = new DecimalFormat("#.##");
        return df.format(kg);
    }


    /**
     * 查询统计总列表
     */
    @PreAuthorize("@ss.hasPermi('consumer:statistic:list')")
    @GetMapping("/list")
    public TableDataInfo list(CStatisticTable cStatisticTable) {
        List<CStatisticTableParam> resultList = new ArrayList<>();
//        startPage();
        List<CStatisticTable> list = cStatisticTableService.getcStatisticTables(cStatisticTable, resultList);
        return getDataTable(list, resultList);
    }

    /**
     * 导出统计总列表
     */
    @PreAuthorize("@ss.hasPermi('consumer:statistic:export')")
    @Log(title = "统计总", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, CStatisticTable cStatisticTable) {
        List<CStatisticTableParam> resultList = new ArrayList<>();
        List<CStatisticTable> list = cStatisticTableService.getcStatisticTables(cStatisticTable, resultList);

//查询公司name 加注笔 kg 总计金额
        String name = "";
        if (SecurityUtils.getDeptId() != null) {
            SysDept sysDept = sysDeptService.selectDeptById(SecurityUtils.getDeptId());
            if (sysDept == null) {
                name = "";
            } else {
                name = sysDept.getDeptName();
            }
        } else {
            name = "";
        }
//        if (SecurityUtils.getDeptId() != 227){
//            price = resultList.get(0).getOrderPrice();
//        }
        String sub = this.queryStatisticCard(cStatisticTable);
        // 使用自定义的 CustomExcelExporter 导出 Excel 并添加标题和副标题
        CustomExcelExporter<CStatisticTableParam> exporter = new CustomExcelExporter<>(CStatisticTableParam.class);
        exporter.exportExcelWithHeader(response, resultList, name + "车用尿素加注统计表", name + "车用尿素加注统计表", sub);
    }

    /**
     * 获取统计总详细信息
     */
    @PreAuthorize("@ss.hasPermi('consumer:statistic:query')")
    @GetMapping(value = "/{statisticId}")
    public AjaxResult getInfo(@PathVariable("statisticId") Integer statisticId) {
        return success(cStatisticTableService.selectCStatisticTableByStatisticId(statisticId));
    }

    /**
     * 新增统计总
     */
    @PreAuthorize("@ss.hasPermi('consumer:statistic:add')")
    @Log(title = "统计总", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody CStatisticTable cStatisticTable) {
        return toAjax(cStatisticTableService.insertCStatisticTable(cStatisticTable));
    }

    /**
     * 修改统计总
     */
    @PreAuthorize("@ss.hasPermi('consumer:statistic:edit')")
    @Log(title = "统计总", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody CStatisticTable cStatisticTable) {
        return toAjax(cStatisticTableService.updateCStatisticTable(cStatisticTable));
    }

    /**
     * 删除统计总
     */
    public AjaxResult remove(@PathVariable Integer[] statisticIds) {
        return toAjax(cStatisticTableService.deleteCStatisticTableByStatisticIds(statisticIds));
    }

    private String queryStatisticCard(CStatisticTable cStatisticTable) {
        System.out.println("cStatisticTable = " + cStatisticTable);
        List<CStatisticTable> cStatisticTables = cStatisticTableService.selectCStatisticTableList(cStatisticTable);

        BigDecimal totalOrderMoney = BigDecimal.ZERO;
        BigDecimal totalOrderFilledKg = BigDecimal.ZERO; // 修改为BigDecimal类型
        int totalTransactions = cStatisticTables.size();

        for (CStatisticTable stat : cStatisticTables) {
            totalOrderMoney = totalOrderMoney.add(BigDecimal.valueOf(stat.getOrderMoney()));
            // 将克(g)转换为千克(kg)，并保留两位小数
            double filledKg = stat.getOrderFilled() / 1000.0;
            totalOrderFilledKg = totalOrderFilledKg.add(BigDecimal.valueOf(filledKg));
        }
        //将单位转为元保留两位小数
        totalOrderMoney = totalOrderMoney.divide(BigDecimal.valueOf(100),
                2, BigDecimal.ROUND_HALF_UP);

        // 格式化保留两位小数
        DecimalFormat df = new DecimalFormat("#.##");
        String totalOrderFilledKgFormatted = df.format(totalOrderFilledKg.doubleValue());

        Map<String, Object> result = new HashMap<>();
        result.put("totalOrderMoney", totalOrderMoney);
        result.put("totalOrderFilledKg", totalOrderFilledKgFormatted);
        result.put("totalTransactions", totalTransactions);

        return createSubtitle(totalTransactions, totalOrderFilledKgFormatted, totalOrderMoney,SecurityUtils.getDeptId());
    }

    public String createSubtitle(int totalTransactions, String totalOrderFilledKg, BigDecimal totalOrderMoney,Long deptId) {
        // 格式化金额和数量为字符串
        String formattedKg = totalOrderFilledKg; // 格式化为两位小数
        String formattedMoney = String.format("%.2f 元", totalOrderMoney.divide(new BigDecimal(100))); // 假设 totalOrderMoney 是以分为单位
        String subtitle ="";
//        if (deptId == 227) {
             subtitle = String.format("加注： %d 笔   数量： %s kg   合计金额： %s", totalTransactions, formattedKg, formattedMoney);
//        } else {
//             subtitle = String.format("加注： %d 笔   数量： %s kg   单价： %s 元  合计金额： %s 元", totalTransactions, formattedKg, price ,formattedMoney);
//        }
        // 拼接副标题字符串


        return subtitle;
    }
}
